/*
 *
 * Copyright (c) 2001-2016 泛微软件.
 * 泛微协同商务系统,版权所有.
 * 
 */
package weaver.ofs.webservices;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.service.invoker.AbstractInvoker;
import org.codehaus.xfire.transport.http.XFireServletController;
import org.codehaus.xfire.util.dom.DOMInHandler;
import org.dom4j.io.DOMReader;
import weaver.integration.cache.OfsSettingCacheNew;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.ofs.manager.IOfsTodoDataManager;
import weaver.ofs.manager.OfsTodoDataManagerNew;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 统一待办webservice接口实现类
 * @author liurui
 */
public class OfsTodoDataWebServiceImpl implements OfsTodoDataWebService {

	private static Logger log = LoggerFactory.getLogger("ofs", OfsTodoDataWebServiceImpl.class.getName());
	 /**
     * 统一待办业务处理对象
     */		
	private IOfsTodoDataManager ofsTodoDataManager = new OfsTodoDataManagerNew();
	/**
	 * 接收待办流程(标准格式)
	 * @param dataMap
	 * @return
	 */
	public Map<String,String> receiveTodoRequestByMap(Map<String,String> dataMap){

		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验

		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);

		return ofsTodoDataManager.receiveTodoRequestByMap(dataMap2);
	}
	
	/**
	 * 处理待办流程（变为已办）(标准格式)
	 * @param dataMap
	 * @return
	 */
	public Map<String,String> processDoneRequestByMap(Map<String,String> dataMap){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);

		return ofsTodoDataManager.processDoneRequestByMap(dataMap2);
	}
	
	/**
	 * 处理办结流程（变为办结）(标准格式)
	 * @param dataMap
	 * @return
	 */
	public Map<String,String> processOverRequestByMap(Map<String,String> dataMap){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);

		return ofsTodoDataManager.processOverRequestByMap(dataMap2);
	}
	
	/**
	 * 接收异构系统流程(标准格式)
	 * @param dataMap
	 * @return
	 */
	public Map<String,String> receiveRequestInfoByMap(Map<String,String> dataMap){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);

		return ofsTodoDataManager.receiveRequestInfoByMap(dataMap2);
	}
	private String getXML(String xmlOld){

		/*MessageContext context = AbstractInvoker.getContext();

		org.w3c.dom.Document localDocument = (org.w3c.dom.Document)context.getInMessage().getProperty("dom.message");*/
//		2021-09-30 EBU7-dev1 ayh修改（项目经理要求）
		MessageContext context;
		org.w3c.dom.Document localDocument;
		try {
			context = AbstractInvoker.getContext();

			localDocument = (org.w3c.dom.Document)context.getInMessage().getProperty("dom.message");
		}catch (Exception e){
			return  xmlOld;
		}
		//		2021-09-30 EBU7-dev1 ayh修改（项目经理要求） end
		if(localDocument != null){
			String xml = buildDocment(localDocument).asXML();
			if(StringUtils.isBlank(xml)){
				return xmlOld;
			}

			int start = xml.indexOf("<in0>");
			int end = xml.indexOf("</in0>");

			if(start<0){

				start = xml.indexOf("<web:in0>");
				start = start+9;
			}else{
				start = start+5;
			}
			if(end<0){
				end = xml.indexOf("</web:in0>");
			}

			xml = xml.substring(start,end);

			log.info("截取需要的xml："+xml);

			xml = StringEscapeUtils.unescapeHtml(xml);

			log.error("getXML:"+xml);

			return xml;
		}else{
			return xmlOld;
		}

	}
	private String getJson(String jsonOld){

		/*MessageContext context = AbstractInvoker.getContext();

		org.w3c.dom.Document localDocument = (org.w3c.dom.Document)context.getInMessage().getProperty(DOMInHandler.DOM_MESSAGE);*/

//		2021-09-30 UEB7-dev1 ayh修改（项目经理提的需求）
		org.w3c.dom.Document localDocument;
		MessageContext context;
		try {
			context = AbstractInvoker.getContext();

			localDocument = (org.w3c.dom.Document)context.getInMessage().getProperty(DOMInHandler.DOM_MESSAGE);
		}catch(Exception e){
			return jsonOld;
		}
//		2021-09-30 UEB7-dev1 ayh修改 end
		if(localDocument != null){
			String xml = buildDocment(localDocument).asXML();
			if(StringUtils.isBlank(xml)){
				return jsonOld;
			}

			int start = xml.indexOf("<in0>");
			int end = xml.indexOf("</in0>");

			if(start<0){

				start = xml.indexOf("<web:in0>");
				start = start+9;
			}else{
				start = start+5;
			}
			if(end<0){
				end = xml.indexOf("</web:in0>");
			}
			String json = xml.substring(start,end);

			log.info("截取需要的json："+json);

			return json;
		}else{
			return jsonOld;
		}

	}
	/**
	 * 接收待办流程(json格式)
	 * @param json
	 * @return
	 */
	public String receiveTodoRequestByJson(String json){

		json = getJson(json);
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验


		return ofsTodoDataManager.receiveTodoRequestByJson(json);
	}
	
	/**
	 * 处理待办流程（变为已办）(json格式)
	 * @param json
	 * @return
	 */
	public String processDoneRequestByJson (String json){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		json = getJson(json);
		return ofsTodoDataManager.processDoneRequestByJson(json);
	}
	
	/**
	 * 处理办结流程（变为办结）(json格式)
	 * @param json
	 * @return
	 */
	public String processOverRequestByJson (String json){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验

		json = getJson(json);
		return ofsTodoDataManager.processOverRequestByJson(json);
	}
	private org.dom4j.Document buildDocment(org.w3c.dom.Document paramDocument)
	{
		DOMReader localDOMReader = new DOMReader();
		return localDOMReader.read(paramDocument);
	}
	/**
	 * 接收异构系统流程(json格式)
	 * @param json
	 * @return
	 */
	public String receiveRequestInfoByJson (String json){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验


		json = getJson(json);
		return ofsTodoDataManager.receiveRequestInfoByJson(json);
	}
	
	/**
	 * 接收待办流程(xml格式)
	 * @param xml
	 * @return
	 */
	public String receiveTodoRequestByXml(String xml){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验

		xml = getXML(xml);
		return ofsTodoDataManager.receiveTodoRequestByXml(xml);
	}
	
	/**
	 * 处理待办流程（变为已办）(xml格式)
	 * @param xml
	 * @return
	 */
	public String processDoneRequestByXml (String xml){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		xml = getXML(xml);

		return ofsTodoDataManager.processDoneRequestByXml(xml);
	}
	
	/**
	 * 处理办结流程（变为办结）(xml格式)
	 * @param xml
	 * @return
	 */
	public String processOverRequestByXml (String xml){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验

		xml = getXML(xml);
		return ofsTodoDataManager.processOverRequestByXml(xml);
	}
	/**
	 * 接收异构系统流程(xml格式)
	 * @param xml
	 * @return
	 */
	public String receiveRequestInfoByXml (String xml){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验

		xml = getXML(xml);
		return ofsTodoDataManager.receiveRequestInfoByXml(xml);
	}
	
	/**
     * XFIRE获取客户端IP地址
     * 
     * @Author MH
     * @return
     */
    private String getClientIpXfire() {
        String ip = "";
        try {
            HttpServletRequest request = XFireServletController.getRequest();
            ip = getRemoteAddress(request);
            return ip;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    
    /**
	* 在JSP里，获取客户端的IP地址的方法是：request.getRemoteAddr()，这种方法在大部分情况下都是有效的。
	* 但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了
	* 经过代理以后，由于在客户端和服务之间增加了中间层，因此服务器无法直接拿到客户端的IP，服务器端应用也无法直接通过转发请求的地址返回给客户端。
	* 但是在转发请求的HTTP头信息中，增加了X－FORWARDED－FOR信息。用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址
	* 如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值,
	* 取X-Forwarded-For中第一个非unknown的有效IP字符串。
	* 
	* @param request
	* @return
	*/
    private String getRemoteAddress(HttpServletRequest request) {  
        String ip = request.getHeader("x-forwarded-for");  
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
            ip = request.getRemoteAddr();  
        }  
        if ((ip.indexOf(",") >= 0)){
			ip = ip.substring(0 , ip.indexOf(","));
		}
        return ip;  
    }
    
    /**
	 * 删除异构系统流程(map格式)
	 * @param dataMap
	 * @return
	 */
	public Map<String, String> deleteRequestInfoByMap(
			Map<String, String> dataMap) {
		// TODO Auto-generated method stub
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);
		return ofsTodoDataManager.deleteRequestInfoByMap(dataMap2);
	}

	 /**
	 * 删除异构系统用户某条流程(map格式)
	 * @param dataMap
	 * @return
	 */
	public Map<String, String> deleteUserRequestInfoByMap(
			Map<String, String> dataMap) {
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);
		return ofsTodoDataManager.deleteUserRequestInfoByMap(dataMap2);
	}
	 /**
	 * 删除异构系统流程(Json格式)
	 * @param json
	 * @return
	 */
	public String deleteRequestInfoByJson(
			String json) {
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		json = getJson(json);
		return ofsTodoDataManager.deleteRequestInfoByJson(json);
	}
	
	 /**
	 * 删除异构系统流程(xml格式)
	 * @param xml
	 * @return
	 */
	public String deleteRequestInfoByXML(
			String xml) {
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		xml = getXML(xml);
		return ofsTodoDataManager.deleteRequestInfoByXML(xml);
	}
	
	 /**
	 * 删除异构系统用户某条流程(json格式)
	 * @param json
	 * @return
	 */
	public String deleteUserRequestInfoByJson(
			String json) {
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		json = getJson(json);
		return ofsTodoDataManager.deleteUserRequestInfoByJson(json);
	}
	 /**
	 * 删除异构系统用户某条流程(xml格式)
	 * @param xml
	 * @return
	 */
	public String deleteUserRequestInfoByXML(
			String xml) {
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		xml = getXML(xml);
		return ofsTodoDataManager.deleteUserRequestInfoByXML(xml);
	}

	/**
	 * 接收抄送流程(json格式)
	 * @param json
	 * @return
	 */
	public String receiveCCRequestByJson(String json){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		json = getJson(json);
		return ofsTodoDataManager.receiveCCRequestByJson(json);
	}

	/**
	 * 接收抄送流程(json格式)
	 */
	public Map<String,String> receiveCCRequestByMap(Map<String,String> dataMap){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);
		return ofsTodoDataManager.receiveCCRequestByMap(dataMap2);
	}

	/**
	 * 接收抄送流程(json格式)
	 * @param xml
	 * @return
	 */
	public String receiveCCRequestByXml(String xml){
		ofsTodoDataManager.setClientIp(getClientIpXfire());//设置当前IP，为了做IP安全校验
		xml = getXML(xml);
		return ofsTodoDataManager.receiveCCRequestByXml(xml);
	}

	/**
	 * 接收抄送流程(json格式)
	 * @param json
	 * @return
	 */
	public String receiveReadRequestByJson(String json){
		ofsTodoDataManager.setClientIp(getClientIpXfire());
		json = getJson(json);
		return ofsTodoDataManager.receiveReadRequestByJson(json);
	}

	/**
	 * 接收抄送流程(json格式)
	 */
	public Map<String,String> receiveReadRequestByMap(Map<String,String> dataMap){
		ofsTodoDataManager.setClientIp(getClientIpXfire());
		Map<String,Object> dataMap2 = new HashMap<String, Object>();
		dataMap2.putAll(dataMap);
		return ofsTodoDataManager.receiveReadRequestByMap(dataMap2);
	}

	/**
	 * 接收抄送流程(json格式)
	 * @param xml
	 * @return
	 */
	public String receiveReadRequestByXml(String xml){
		ofsTodoDataManager.setClientIp(getClientIpXfire());
		xml = getXML(xml);
		return ofsTodoDataManager.receiveReadRequestByXml(xml);
	}
}
